//
//  BaseNavigationController.swift
//  SwitfTest
//
//  Created by runone02 on 2018/12/28.
//  Copyright © 2018年 liqiyun. All rights reserved.
//

import UIKit

class BaseNavigationController: KLTNavigationController,UINavigationControllerDelegate {
    override var preferredStatusBarStyle : UIStatusBarStyle{
        get{
            return .default
        }
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBar.isTranslucent = false
        navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.black,NSAttributedString.Key.font:UIFont.systemFont(ofSize: 17)]
        navigationBar.setBackgroundImage(imageWithColor(RGBAlpa(255,255,255,1)), for: .default)
    }
    
    func imageWithColor(_ color:UIColor) -> UIImage? {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        let ctx = UIGraphicsGetCurrentContext()
        ctx?.setFillColor(color.cgColor)
        ctx?.fill(rect)
        let ig = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return ig
    }
    
    
    /// 返回按钮
    func leftBarButtonItem() -> UIBarButtonItem{
        let backBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 40))
        backBtn.setImage(UIImage(named: "leftbackicon_sdk_login"), for: .normal)
        backBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 10)
        backBtn.addTarget(self, action: #selector(navigationBack), for: .touchUpInside)
        let leftitem = UIBarButtonItem.init(customView: backBtn)
        return leftitem
    }

    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        if self.viewControllers.count > 0 {
            viewController.navigationItem.leftBarButtonItem = leftBarButtonItem()
            viewController.hidesBottomBarWhenPushed = true
        }
        self.navigationBar.barTintColor = colorWith(viewController)
       super.pushViewController(viewController, animated: animated)
    }
    
    func colorWith(_ controller:UIViewController) -> UIColor {
        let b = controller.responds(to: Selector.init(("t_barTintColor")))
        var color = RGBAlpa(251,251,251,1)
        if b {
            color = (controller.value(forKey: "t_barTintColor") as? UIColor) ?? RGBAlpa(251,251,251,1)
        }
       return color
    }
    
    override func popViewController(animated: Bool) -> UIViewController? {
        let cnt = self.viewControllers.count
        let last = self.viewControllers[cnt - 2]
        self.navigationBar.barTintColor = colorWith(last)
        return super.popViewController(animated: animated)
    }
    
    /// 点击返回
    @objc func navigationBack(){
    _ = self.popViewController(animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
